<template>
  <div class="header-tool">
    <message-drawer ref="messageDrawerRef" />
    <div class="left no-drag">
      <el-button class="search-button" @click="router.back()">
        <el-icon>
          <i-bi-chevron-left />
        </el-icon>
      </el-button>

      <el-input v-model="searchVal" style="width: 240px" placeholder="搜索感兴趣的" clearable @change="searchAll">
      </el-input>
    </div>
    <div class="right no-drag">
      <div v-if="isLogin">
        <el-popover
          :width="300"
          trigger="click"
          @show="getProfile"
          :hide-after="0"
          popper-class="user-popover"
          :teleported="true"
          :show-arrow="false"
          v-model:visible="popoverVisible"
        >
          <template #reference>
            <div style="display: flex;align-items: center;">
              <el-avatar :src="userInfo.avatarUrl" :size="25" />
              <span>{{ userInfo.nickname }}</span>
            </div>
          </template>
          <template #default>
            <div class="user-card">
              <div class="event-count">
                <div class="count-item" @click="router.push('/user/event')">
                  <span class="count">{{profile.eventCount}}</span>
                  <span class="label">动态</span>
                </div>
                <div class="count-item" @click="router.push('/user/follows')">
                  <span class="count">{{profile.follows}}</span>
                  <span class="label">关注</span>
                </div>
                <div class="count-item" @click="router.push('/user/fans')">
                  <span class="count">{{profile.followeds}}</span>
                  <span class="label">粉丝</span>
                </div>
              </div>
              <el-divider />
              <div class="menu-list">
                <div class="menu-item">
                  <el-icon><User /></el-icon>
                  <span>会员中心</span>
                </div>
                <div class="menu-item">
                  <el-icon class="custom-icon"><i-bi-award /></el-icon>
                  <span>等级</span>
                </div>
                <div class="menu-item">
                  <el-icon class="custom-icon"><i-bi-shop /></el-icon>
                  <span>商城</span>
                </div>
                <div class="menu-item">
                  <el-icon class="custom-icon"><i-bi-gear /></el-icon>
                  <span>个人信息设置</span>
                </div>
                <div class="menu-item">
                  <el-icon class="custom-icon"><i-bi-link-45deg /></el-icon>
                  <span>绑定社交账号</span>
                </div>
                <div class="menu-item">
                  <el-icon class="custom-icon"><i-bi-headset /></el-icon>
                  <span>我的客服</span>
                </div>
                <el-divider />
                <div class="menu-item">
                  <el-icon class="custom-icon"><i-bi-arrow-repeat /></el-icon>
                  <span>切换账号</span>
                </div>
                <div class="menu-item" @click.stop="logout">
                  <el-icon class="custom-icon"><i-bi-box-arrow-right /></el-icon>
                  <span>退出登录</span>
                </div>
              </div>
            </div>
          </template>
        </el-popover>
      </div>
      <div v-else @click.stop="openLogin">
        <el-avatar :icon="UserFilled" :size="25" />
        <p>未登录</p>
      </div>
      <el-icon class="message-trigger" @click.stop="toggleMessagePanel">
        <i-bi-chat-left-dots />
      </el-icon>
      <el-icon @click.stop="router.push('/apidoc')">
        <i-bi-code-slash />
      </el-icon>
      <el-icon @click.stop="router.push('/setting/test')">
        <i-bi-nut />
      </el-icon>
      <el-icon @click="router.push('/setting/theme')">
        <i-bi-palette />
      </el-icon>
      <el-divider direction="vertical" />
      <el-icon @click="winSize('window-min')">
        <i-bi-dash-lg />
      </el-icon>
      <el-icon @click="winSize('window-max')">
        <i-bi-app />
      </el-icon>
      <el-icon @click="winSize('window-close')">
        <i-bi-x-lg />
      </el-icon>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, onMounted, onBeforeUnmount } from 'vue'
import { useUserStore } from "@/store/UserStore";
import { UserFilled, User } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { getUserInfo, logout } from "@/assets/apis/http";
import {UserInfo} from "@/assets/apis/UserDataType";
import MessageDrawer from './MessageDrawer.vue'
import emitter from '@/store/emitter'

const usertore = useUserStore();
const router = useRouter();
const searchVal = ref("");
const userInfo = computed<UserInfo>(() => {
  return usertore.userInfo;
});
let isLogin = computed(() => {
  return usertore.isLogin;
});
const profile = reactive({
  eventCount: 0,
  follows: 0,
  followeds: 0
})
const popoverVisible = ref(false)
const messageDrawerRef = ref()

function searchAll() {
  const keywords = searchVal.value.trim();
  console.log("关键字",keywords)
  if (!keywords) {  return; }
  router.push({ path: '/search', query: { keywords: keywords } });
}
function getProfile(){
  getUserInfo({ uid: userInfo.value.userId }).then((res) => {
    console.log("获取用户基本信息",res.profile)
    profile.eventCount = res.profile.eventCount
    profile.follows = res.profile.follows
    profile.followeds = res.profile.followeds
  });
}
function winSize(type: string) {
  window.electron.ipcRenderer.send(type);
}

function openLogin() {
  usertore.loginDialogVisible = true;
  console.log(usertore.loginDialogVisible);
}


//退出登录
async function logout() {
  await logout();
  usertore.userInfo = <UserInfo> {};
  usertore.isLogin = false;
  router.push({path: router.currentRoute.value.path});
}

// 添加全局点击事件处理
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  // 如果点击的不是popover内部元素且popover是打开的，则关闭popover
  if (!target.closest('.user-popover') &&
      !target.closest('.el-avatar') &&
      !target.closest('.el-popover__reference') &&
      popoverVisible.value) {
    popoverVisible.value = false
  }
}

const toggleMessagePanel = () => {
  emitter.emit('toggleMessagePanel')
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style lang="scss" scoped>
.header-tool {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--el-text-color-regular);
  background-color: var(--bg-bar-header);
  //支持拖动窗体
  -webkit-app-region: drag;
  padding: 20px;
  .ep-icon {
    cursor: pointer;
  }
}

// 不可拖拽区域
.no-drag {
  -webkit-app-region: no-drag;
}

.search-button {
  --ep-button-bg-color: transparent;
}

.left {
  display: flex;
  gap: 10px;
  --ep-input-bg-color: transparent;
}

.right {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: space-around;
  gap: 12px;
  font-size: 20px;
  cursor: pointer;
  position: relative;
  z-index: 1;

  > div {
    cursor: pointer;
    font-size: 13px;
    display: flex;
    align-items: center;
    --ep-avatar-size: 30px;
    z-index: 1; // 确保点击事件能够正常触发

    span {
      margin-right: 10px;
    }
  }

  .ep-icon {
    color: var(--ep-menu-text-color);
  }
}

.user-card {
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
  color: var(--el-text-color-regular);

  .event-count {
    display: flex;
    justify-content: space-around;
    padding: 10px 0;

    .count-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      padding: 0 20px;

      .count {
        font-size: 25px;
        font-weight: normal;
        margin-bottom: 4px;
      }

      .label {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }

      &:hover {
        .count, .label {
          color: var(--el-color-primary);
        }
      }
    }
  }

  .menu-list {
    display: flex;
    flex-direction: column;
  }

  .menu-item {
    display: flex;
    align-items: center;
    padding: 12px 20px;
    font-size: 14px;
    cursor: pointer;

    .el-icon, .custom-icon {
      font-size: 16px;
      margin-right: 8px;
    }

    &:hover {
      background: var(--el-fill-color-light);
    }
  }

  :deep(.el-divider--horizontal) {
    margin: 8px 0;
  }
}

// 添加全局样式
:global(.user-popover) {
  z-index: 2000 !important;
}
</style>
